import request from './request'
import Interface from './interface'
import { App } from 'vue';
interface Api {
    install: (app: App) => void;
    [key: string]: ((params: any) => any) | (<T>(app: T) => void);
}


const api: Api = {
    install: function (app: App) {
        (app as any).config.globalProperties.$api = this;
    }
};

interface RequestOptions {
    url: string;
    method: string;
    params?: any;
    data?: any;
}
Interface.forEach(v => {
    if (!v.desc) {
        console.error('你的方法没有添加描述信息！')
        return
    }
    api[v.name] = (params: any) => {
        // 过滤空参数
        if (params && JSON.stringify(params) !== '{}') {
            let arr = Object.keys(params)
            arr.forEach(item => {
                if (params[item] === null || params[item] === undefined) {
                    delete params[item]
                }
            })
        }

        let { path, method } = v
        let options: RequestOptions = {
            url: path,
            method
        }
        if (method.toLowerCase() == 'get') {
            options = {
                ...options,
                params
            }
        } else {
            options = {
                ...options,
                data: params
            }
        }
        return request(options)
    }
})

export default api